import React, { Component } from 'react';
import {connect} from 'react-redux'
import {
  Form,
  Input,
  InputNumber,
  Cascader,
  Select,
  Row,
  Col,
  Checkbox,
  Button,
  AutoComplete,
  message,
  Modal,
  Popover,
  Spin
} from 'antd';

// 引入自定义的组件
import { GetCaptchaSaga } from '../../redux/actions/register'
import { DoForgetPasswd, DoForgetPasswdSaga, ChangeForgetPasswdActivate } from '../../redux/actions/forgetpasswd'
import { DoLogin } from '../../redux/actions/login'
import { ChangeSpinACtivate } from '../../redux/actions/public'
import { API_URL_GO } from '../../env'

const { Option } = Select;

// 类似样式，调节方框的距离
const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 6,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
};

class ForgetPasswdForm extends Component {

  state = {
    email: '', // 用这个来检测输入邮箱的变化，在点击发送验证码的时候，携带这个参数去请求
    getCaptchaValue: '获取验证码', // 点击后会改变文本框，出现倒计时
    disabled: false
  }

  componentDidUpdate() {
    const { DoLogin, DoForgetPasswd, ChangeSpinACtivate, DoForgetPasswdState, ChangeForgetPasswdActivate } = this.props
    if (DoForgetPasswdState.email_error){
      message.warning("该邮箱还没注册账号")
      DoForgetPasswd({email_error: false})
    }
    if (DoForgetPasswdState.captcha_error){
      message.warning("输入验证码错误, 或者验证码已过期")
      DoForgetPasswd({captcha_error: false})
    }
    if (DoForgetPasswdState.success){
      // ChangeSpinACtivate({activate: false})
      Modal.success({
        title: '修改成功',
        content: (
          <div>
            <p>请您牢记自己的新密码</p>
          </div>
        ),
        onOk() {
          ChangeForgetPasswdActivate({activate:false})
          DoForgetPasswd({success: false})
          DoLogin({activate: true})
          ChangeSpinACtivate({forgetpasswd_activate: false})
        }
      })
    }
  }

  // 点击提交按钮
  onFinish = (values) => {
    console.log('Received values of form: ', values);
    this.props.DoForgetPasswdSaga(values)
    this.props.ChangeSpinACtivate({forgetpasswd_activate: true})
  };

  // 点击获取验证码按钮
  onGetCaptcha = () => {
    // 验证是否输入的是否是邮箱
    var reg = /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/;
    if (reg.test(this.state.email)){
      this.props.GetCaptchaSaga(this.state)
      this.setState({
        disabled:true
      })
      message.success("验证码已发送, 请注意查收")
      // 获取验证码成功，则进入倒计时
      var countDown=30;
      // 定时器
      var timer = setInterval(() => {
        if(countDown > 0){
          this.setState({
            getCaptchaValue: countDown+"秒后重新发送"
          })
        }else{
            // 如果不需要倒计时，则清除，否则会一直执行
            clearInterval(timer);
            this.setState({
              getCaptchaValue: "获取验证码",
              disabled: false
            })
        }
        countDown -= 1;
      }, 1000);
    } else{
      message.error("输入邮箱账号再请求验证码")
    }
  }

  handleChangeEmail = (e) => {
    this.setState({
      email: e.target.value
    }) 
  }

  render(){
    const { SpinState } = this.props
    return (
      <Form
        {...formItemLayout}
        name="register"
        onFinish={this.onFinish}
        scrollToFirstError
      >
        <Form.Item
          name="email"
          label="邮箱账号"
          rules={[
            {
              type: 'email',
              message: '请输入正确的邮箱格式!',
            },
            {
              required: true,
              message: '请输入您的邮箱!',
            },
          ]}
        >
          <Input onChange={this.handleChangeEmail} />
        </Form.Item>

        <Form.Item
          name="password"
          label="重置密码"
          rules={[
            {
              required: true,
              message: '请输入您新的密码!',
            },
          ]}
          hasFeedback
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          name="confirm"
          label="确认密码"
          dependencies={['password']}
          hasFeedback
          rules={[
            {
              required: true,
              message: '请再次输入您新的密码!',
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }

                return Promise.reject(new Error('您现在输入的密码和上次输入的密码不相同!'));
              },
            }),
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item label="验证码" extra="我们希望是您本人操作!">
          <Row gutter={8}>
            <Col span={12}>
              <Form.Item
                name="captcha"
                noStyle
                rules={[
                  {
                    required: true,
                    message: '请输入您邮箱获取到的验证码!',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Button onClick={this.onGetCaptcha} disabled={this.state.disabled}>{this.state.getCaptchaValue}</Button>
            </Col>
          </Row>
        </Form.Item>

        <Spin spinning={ SpinState.forgetpasswd_activate } tip="重置中......">
          <Form.Item {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit">
              提交新密码
            </Button>
            {
              this.state.email 
              ? 
              <a href={API_URL_GO + "register/get_captcha/" + this.state.email} target="_blank" >&nbsp;收不到验证码</a>
              :
              <></>
            }
          </Form.Item>
        </Spin>
      </Form>
    );
  }
};

export default connect(
  state => ({
    SpinState: state.PublicReducer.spinState,
    DoForgetPasswdState: state.ForgetPasswdReducer.doForgetPasswdState
  }),
  {
    GetCaptchaSaga, // 获取注册验证码
    DoLogin,
    ChangeSpinACtivate, // 共用的加载状态
    DoForgetPasswdSaga, // 向后端请求修改密码
    DoForgetPasswd, // 记录密码修改是否成功
    ChangeForgetPasswdActivate, // 改变忘记密码弹窗状态
  }
)(ForgetPasswdForm) 